package com.itheima.interceptor;

import com.itheima.common.JwtUtil;
import com.itheima.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 访问资源拦截器:拦截请求判断携带的token是否合法
 * @Author: hsp
 * @Date: 2022/11/19-11-19-23:21
 * @Description: com.itheima.interceptor
 * @version: 1.0.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    //拦截校验
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 从请求头获取token  这里不是session
        String token = request.getHeader("token");

        try {
            //2. 视图解析token合法就放行
            Map map = JwtUtil.parseToken(token);
            Object id = map.get("id");
            //根据id从数据库查询用户 /  redis中查询


            //token合法就放行
            return true;
        } catch (Exception e){
            //校验失败，不放行,并给出提示
            //401 状态码是身份验证失败
            response.setStatus(401);
            return false;
        }

    }
}
